package com.buaa.aimall.goodsModule.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buaa.aimall.Utils.Client.BUAAComputeClient;
import com.buaa.aimall.Utils.Client.KongAPIGatewayClient;
import com.buaa.aimall.Utils.Config.KongAPIGatewayConfig;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.goodsModule.Entity.GoodsOrderEntity;
import com.buaa.aimall.goodsModule.DTO.FilterOrderDTO;
import com.buaa.aimall.goodsModule.Entity.GoodsOrderAppealWorkOrderEntity;
import com.buaa.aimall.goodsModule.Enum.GoodsTypeEnum;
import com.buaa.aimall.goodsModule.Enum.GoodsOrderSortTypeEnum;
import com.buaa.aimall.modelModule.Entity.ModelEntity;
import com.buaa.aimall.modelModule.Entity.ModelResourceEntity;
import com.buaa.aimall.modelModule.Service.ModelAPIService;
import com.buaa.aimall.modelModule.Service.ModelResourceService;
import com.buaa.aimall.modelModule.Service.ModelService;
import com.buaa.aimall.userModule.Entity.UserEntity;
import com.buaa.aimall.Utils.Exception.BusinessException;
import com.buaa.aimall.goodsModule.Mapper.GoodsOrderMapper;
import com.buaa.aimall.userModule.Service.UserService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;


import com.buaa.aimall.goodsModule.DTO.CreateOrderDTO;
import com.buaa.aimall.goodsModule.Converter.OrderConvert;
import com.buaa.aimall.computeModule.Entity.ComputeEntity;
import com.buaa.aimall.computeModule.Entity.ComputeResourceEntity;
import com.buaa.aimall.computeModule.Service.ComputeService;
import com.buaa.aimall.goodsModule.DTO.UserOrderStatsDTO;
import com.buaa.aimall.goodsModule.Entity.TransactionOrderEntity;
import com.buaa.aimall.Utils.Enum.PaymentStatus;
import com.buaa.aimall.userModule.Entity.ShoppingCartEntity;
import com.buaa.aimall.userModule.Service.ShoppingCartService;
import com.buaa.aimall.goodsModule.Entity.CouponEntity;
import com.buaa.aimall.Utils.Enum.ChargeTypeEnum;
import com.buaa.aimall.computeModule.Service.ComputeResourceService;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrderEntity>
        implements GoodsOrderService {

    @Autowired
    private UserService userService;

    @Autowired
    private ModelService modelService;

    @Autowired
    private ComputeService computeService;

    @Autowired
    private TransactionOrderService transactionOrderService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private ComputeResourceService computeResourceService;

    @Autowired
    private ModelAPIService modelAPIService;

    @Autowired
    private ModelResourceService modelResourceService;

    @Autowired
    private KongAPIGatewayClient kongAPIGatewayClient;

    @Autowired
    private KongAPIGatewayConfig kongAPIGatewayConfig;

    private final BUAAComputeClient buaaComputeClient;

    public GoodsOrderServiceImpl(BUAAComputeClient buaaComputeClient) {
        this.buaaComputeClient = buaaComputeClient;
    }

    private Integer calculateDiscountedAmount(int modelTotalAmount, int computeTotalAmount, String modelCouponId, String computeCouponId) {
        var modelCoupon = couponService.getById(modelCouponId);
        var computeCoupon = couponService.getById(computeCouponId);
        var totalAmount = modelTotalAmount + computeTotalAmount;
        if (modelCoupon != null) {
            if (modelCoupon.getUsefor() != GoodsTypeEnum.MODEL) {
                throw new BusinessException("优惠券类型错误，" + modelCouponId + "不是模型优惠券");
            }
            if (modelCoupon.getExpirationTime().isBefore(LocalDateTime.now())) {
                throw new BusinessException("模型优惠券已过期");
            }
            totalAmount = totalAmount - modelTotalAmount + (int) Math.ceil(modelTotalAmount * (modelCoupon.getDiscount() / 100.0));
        }
        if (computeCoupon != null) {
            if (computeCoupon.getUsefor() != GoodsTypeEnum.COMPUTE) {
                throw new BusinessException("优惠券类型错误，" + modelCouponId + "不是算力优惠券");
            }
            if (computeCoupon.getExpirationTime().isBefore(LocalDateTime.now())) {
                throw new BusinessException("算力优惠券已过期");
            }
            totalAmount = totalAmount - computeTotalAmount + (int) Math.ceil(computeTotalAmount * (computeCoupon.getDiscount() / 100.0));
        }
        return totalAmount;
    }

    private void consumeCoupon(String couponId) {
        if (couponId != null) {
            CouponEntity coupon = couponService.getById(couponId);
            if (coupon == null) {
                throw new BusinessException("优惠券不存在");
            }
            if (coupon.getExpirationTime().isBefore(LocalDateTime.now())) {
                throw new BusinessException("优惠券已过期");
            }
            if (coupon.getUsageTimes() > 0) {
                coupon.setUsageTimes(coupon.getUsageTimes() - 1);
                couponService.updateById(coupon);
            } else if (coupon.getUsageTimes() == 0 || coupon.getUsageTimes() <= -2) {
                throw new BusinessException("优惠券已使用次数达到上限");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public TransactionOrderEntity createOrders(List<CreateOrderDTO> createOrderDTOs, String modelCouponId, String computeCouponId) {
        if (createOrderDTOs == null || createOrderDTOs.isEmpty()) {
            throw new BusinessException("订单列表不能为空");
        }

        // 先进行所有订单的验证
        for (CreateOrderDTO createOrderDTO : createOrderDTOs) {
            // 验证modelID和computeID的互斥性
            if ((createOrderDTO.getModelID() == null && createOrderDTO.getComputeID() == null) ||
                    (createOrderDTO.getModelID() != null && createOrderDTO.getComputeID() != null)) {
                throw new BusinessException("modelID和computeID必须且只能存在一个");
            }

            // 验证ID对应的内容是否存在
            if (createOrderDTO.getModelID() != null) {
                ModelEntity model = modelService.getById(createOrderDTO.getModelID());
                if (model == null) {
                    throw new BusinessException("指定的模型不存在");
                }
            } else {
                ComputeEntity compute = computeService.getById(createOrderDTO.getComputeID());
                if (compute == null) {
                    throw new BusinessException("指定的计算资源不存在");
                }
            }
        }

        // 创建TransactionOrder
        TransactionOrderEntity transactionOrderEntity = new TransactionOrderEntity();
        transactionOrderEntity.setPaymentStatus(PaymentStatus.PAYING);
        transactionOrderEntity.setCreateTime(LocalDateTime.now());
        transactionOrderEntity.setBuyerID(userService.getCurrentUser().getId());

        // 计算总金额
        int modelTotalAmount = 0;
        int computeTotalAmount = 0;
        for (CreateOrderDTO createOrderDTO : createOrderDTOs) {
            if (createOrderDTO.getModelID() != null) {
                ModelEntity model = modelService.getById(createOrderDTO.getModelID());
                modelTotalAmount += calculateModelAmount(model, createOrderDTO.getType(), createOrderDTO.getQuantity());
            } else {
                ComputeEntity compute = computeService.getById(createOrderDTO.getComputeID());
                computeTotalAmount += calculateComputeAmount(compute, createOrderDTO.getType(), createOrderDTO.getQuantity());
            }
        }
        int totalAmount = calculateDiscountedAmount(modelTotalAmount, computeTotalAmount, modelCouponId, computeCouponId);
        transactionOrderEntity.setTotalAmount(totalAmount);
        transactionOrderEntity.setModelCouponID(modelCouponId);
        transactionOrderEntity.setComputeCouponID(computeCouponId);

        // 保存TransactionOrder
        boolean transactionSaveResult = transactionOrderService.save(transactionOrderEntity);
        if (!transactionSaveResult) {
            throw new BusinessException("交易订单创建失败");
        }

        // 创建并保存所有GoodsOrder
        for (CreateOrderDTO createOrderDTO : createOrderDTOs) {
            GoodsOrderEntity goodsOrderEntity = OrderConvert.INSTANCE.dtoToEntity(createOrderDTO);
            goodsOrderEntity.setCreateTime(LocalDateTime.now());
            goodsOrderEntity.setTransactionOrderID(transactionOrderEntity.getId());
            goodsOrderEntity.setBuyerID(userService.getCurrentUser().getId());

            boolean saveResult = this.save(goodsOrderEntity);
            if (!saveResult) {
                throw new BusinessException("订单创建失败");
            }
        }
        return transactionOrderEntity;
    }

    public List<GoodsOrderEntity> getModelOrderListByModelId(String modelId) {
        UserEntity userEntity = userService.getCurrentUser();
        ModelEntity modelEntity = modelService.getById(modelId);
        if (modelEntity == null) {
            throw new BusinessException("模型不存在");
        }
        if (!modelEntity.getCreator().equals(userEntity.getId())) {
            throw new BusinessException("无权访问该模型信息");
        }
        LambdaQueryWrapper<GoodsOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsOrderEntity::getModelID, modelEntity.getId());
        return this.list(queryWrapper);
    }

    @Override
    public PageReturnResult<GoodsOrderEntity> filterOrder(FilterOrderDTO filterOrderDTO) {
        if (filterOrderDTO.getOrderType() == null) {
            throw new BusinessException("订单类型不能为空");
        }
        PageReturnResult<GoodsOrderEntity> result = new PageReturnResult<>();
        MPJLambdaWrapper<GoodsOrderEntity> queryWrapper = new MPJLambdaWrapper<>();

        // 动态过滤条件
        if (filterOrderDTO.getId() != null)
            queryWrapper.eq(GoodsOrderEntity::getId, filterOrderDTO.getId());
        if (filterOrderDTO.getModelID() != null)
            queryWrapper.eq(GoodsOrderEntity::getModelID, filterOrderDTO.getModelID());
        if (filterOrderDTO.getComputeID() != null)
            queryWrapper.eq(GoodsOrderEntity::getComputeID, filterOrderDTO.getComputeID());
        if (filterOrderDTO.getBuyerID() != null)
            queryWrapper.eq(GoodsOrderEntity::getBuyerID, filterOrderDTO.getBuyerID());
        if (filterOrderDTO.getAmountMin() != null)
            queryWrapper.ge(GoodsOrderEntity::getAmount, filterOrderDTO.getAmountMin());
        if (filterOrderDTO.getAmountMax() != null)
            queryWrapper.le(GoodsOrderEntity::getAmount, filterOrderDTO.getAmountMax());
        if (filterOrderDTO.getCreateTimeStart() != null)
            queryWrapper.ge(GoodsOrderEntity::getCreateTime, filterOrderDTO.getCreateTimeStart());
        if (filterOrderDTO.getCreateTimeEnd() != null)
            queryWrapper.le(GoodsOrderEntity::getCreateTime, filterOrderDTO.getCreateTimeEnd());
        if (filterOrderDTO.getType() != null)
            queryWrapper.eq(GoodsOrderEntity::getType, filterOrderDTO.getType().code);
        if (filterOrderDTO.getQuantity() != null)
            queryWrapper.eq(GoodsOrderEntity::getQuantity, filterOrderDTO.getQuantity());
        if (filterOrderDTO.getSort() != null) {
            addSortConditions(queryWrapper, filterOrderDTO.getSort().getCode());
        } else {
            addSortConditions(queryWrapper, GoodsOrderSortTypeEnum.DEFAULT.getCode());
        }

        // 根据orderType过滤不同类型的订单
        if (filterOrderDTO.getOrderType() == 0) {
            queryWrapper.isNotNull(GoodsOrderEntity::getModelID);
        } else if (filterOrderDTO.getOrderType() == 1) {
            queryWrapper.isNotNull(GoodsOrderEntity::getComputeID);
        }

        queryWrapper.selectAll(GoodsOrderEntity.class) // 选择 ModelOrderEntity 的所有字段
                .select(GoodsOrderAppealWorkOrderEntity::getStatus)
                .leftJoin(GoodsOrderAppealWorkOrderEntity.class, GoodsOrderAppealWorkOrderEntity::getGoodsOrderID,
                        GoodsOrderEntity::getId);

        // 分页逻辑
        Integer pageSize = filterOrderDTO.getPageSize();
        Integer currentPage = filterOrderDTO.getCurrentPage();

        // 先获取符合条件的总记录数
        List<GoodsOrderEntity> allMatchingOrders = this.listDeep(queryWrapper);
        List<GoodsOrderEntity> filteredOrders = allMatchingOrders.stream()
                .filter(order -> {
                    if (filterOrderDTO.getOrderType() == 0) {
                        ModelEntity model = modelService.getById(order.getModelID());
                        return model != null && model.getDelFlag() != 1;
                    } else {
                        ComputeEntity compute = computeService.getById(order.getComputeID());
                        return compute != null && compute.getDelFlag() != 1;
                    }
                })
                .collect(Collectors.toList());
        result.setTotalCount(filteredOrders.size());

        // 应用分页
        if (pageSize != null && currentPage != null) {
            int fromIndex = (currentPage - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, filteredOrders.size());

            // 防止索引越界
            if (fromIndex < filteredOrders.size()) {
                result.setRecords(filteredOrders.subList(fromIndex, toIndex));
            } else {
                result.setRecords(new ArrayList<>());
            }
        } else {
            result.setRecords(filteredOrders);
        }

        return result;
    }

    public UserOrderStatsDTO getUserOrderStats(Integer orderType, String userId) {
        UserOrderStatsDTO stats = new UserOrderStatsDTO();

        // 获取用户余额
        UserEntity user = userService.getById(userId);
        if (user != null) {
            stats.setCurrentBalance(user.getIncome());
        }

        MPJLambdaWrapper<GoodsOrderEntity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(GoodsOrderEntity.class);

        // 根据订单类型筛选
        if (orderType == 0) {
            queryWrapper.isNotNull(GoodsOrderEntity::getModelID)
                    .leftJoin(ModelEntity.class, ModelEntity::getId, GoodsOrderEntity::getModelID)
                    .eq(ModelEntity::getCreator, userId);
        } else {
            queryWrapper.isNotNull(GoodsOrderEntity::getComputeID)
                    .leftJoin(ComputeEntity.class, ComputeEntity::getId, GoodsOrderEntity::getComputeID)
                    .eq(ComputeEntity::getCreator, userId);
        }

        List<GoodsOrderEntity> orders = this.listDeep(queryWrapper);

        // 计算统计数据
        stats.setTotalIncome(orders.stream()
                .mapToInt(GoodsOrderEntity::getAmount)
                .sum());

        stats.setTotalUsage(orders.size());

        stats.setMaxAmount(orders.stream()
                .mapToInt(GoodsOrderEntity::getAmount)
                .max()
                .orElse(0));

        return stats;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean payTransaction(String transactionId, Boolean isSuccess) {
        // 1. 获取交易订单
        TransactionOrderEntity transactionOrder = transactionOrderService.getById(transactionId);
        if (transactionOrder == null) {
            throw new BusinessException("交易订单不存在");
        }

        // 2. 检查订单状态
        if (!(transactionOrder.getPaymentStatus() == PaymentStatus.PAYING)) {
            throw new BusinessException("订单状态异常，请勿重复支付");
        }

        // 3. 获取当前用户
        UserEntity currentUser = userService.getCurrentUser();
        if (!currentUser.getId().equals(transactionOrder.getBuyerID())) {
            throw new BusinessException("无权支付此订单");
        }

        // 如果支付不成功，直接更新订单状态为失败并返回
        if (!isSuccess) {
            transactionOrder.setPaymentStatus(PaymentStatus.FAILED);
            boolean updateResult = transactionOrderService.updateById(transactionOrder);
            return updateResult;
        }

        // 4. 检查用户余额是否足够
        if (currentUser.getBalance() < transactionOrder.getTotalAmount()) {
            throw new BusinessException("余额不足，请充值后再支付");
        }

        // 5. 获取该交易下的所有商品订单
        LambdaQueryWrapper<GoodsOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsOrderEntity::getTransactionOrderID, transactionId);
        List<GoodsOrderEntity> goodsOrders = this.list(queryWrapper);

        if (goodsOrders.isEmpty()) {
            throw new BusinessException("该交易下没有商品订单");
        }
        // 6. 更新买家余额
        currentUser.setBalance(currentUser.getBalance() - transactionOrder.getTotalAmount());
        boolean updateBuyerResult = userService.updateById(currentUser);
        if (!updateBuyerResult) {
            throw new BusinessException("更新买家余额失败");
        }

        // 7. 更新每个商品订单对应卖家的收入
        for (GoodsOrderEntity goodsOrder : goodsOrders) {
            String sellerId = null;

            // 根据订单类型获取卖家ID
            if (goodsOrder.getModelID() != null) {
                ModelEntity model = modelService.getById(goodsOrder.getModelID());
                if (model == null) {
                    throw new BusinessException("模型不存在");
                }
                createModelResource(goodsOrder, model);
                sellerId = model.getCreator();
            } else if (goodsOrder.getComputeID() != null) {
                ComputeEntity compute = computeService.getById(goodsOrder.getComputeID());
                if (compute == null) {
                    throw new BusinessException("计算资源不存在");
                }
                createComputeResource(goodsOrder, compute);
                sellerId = compute.getCreator();
            }

            if (sellerId != null) {
                // 更新卖家余额
                UserEntity seller = userService.getById(sellerId);
                if (seller != null) {
                    seller.setIncome(seller.getIncome() + goodsOrder.getAmount());
                    boolean updateSellerResult = userService.updateById(seller);
                    if (!updateSellerResult) {
                        throw new BusinessException("更新卖家余额失败");
                    }
                }
            }
        }

        // 8. 更新交易订单状态为已支付
        transactionOrder.setPaymentStatus(PaymentStatus.SUCCESS);
        consumeCoupon(transactionOrder.getModelCouponID());
        consumeCoupon(transactionOrder.getComputeCouponID());
        boolean updateTransactionResult = transactionOrderService.updateById(transactionOrder);
        if (!updateTransactionResult) {
            throw new BusinessException("更新交易订单状态失败");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TransactionOrderEntity createOrdersFromCart(List<String> cartItemIds, String modelCouponId, String computeCouponId) {
        if (cartItemIds == null || cartItemIds.isEmpty()) {
            throw new BusinessException("购物车商品ID列表不能为空");
        }

        // 获取当前用户
        UserEntity currentUser = userService.getCurrentUser();

        // 获取购物车项
        List<ShoppingCartEntity> cartItems = new ArrayList<>();
        for (String id : cartItemIds) {
            ShoppingCartEntity cartItem = shoppingCartService.getById(id);
            if (cartItem == null) {
                throw new BusinessException("购物车商品不存在：" + id);
            }

            // 验证购物车项是否属于当前用户
            if (!cartItem.getCreator().equals(currentUser.getId())) {
                throw new BusinessException("无权操作他人的购物车商品");
            }

            cartItems.add(cartItem);
        }

        // 转换为订单DTO
        List<CreateOrderDTO> orderDTOs = new ArrayList<>();
        for (ShoppingCartEntity cartItem : cartItems) {
            CreateOrderDTO orderDTO = new CreateOrderDTO();
            orderDTO.setModelID(cartItem.getModelID());
            orderDTO.setComputeID(cartItem.getComputeID());
            orderDTO.setType(cartItem.getType());
            orderDTO.setQuantity(cartItem.getQuantity());

            // 计算订单金额（这里需要根据实际业务逻辑计算）
            Integer amount = calculateAmount(cartItem);
            orderDTO.setAmount(amount);

            orderDTOs.add(orderDTO);
        }

        // 创建订单
        TransactionOrderEntity result = createOrders(orderDTOs, modelCouponId, computeCouponId);

        // 删除购物车项
        if (result != null) {
            for (String id : cartItemIds) {
                shoppingCartService.removeById(id);
            }
        }

        return result;
    }

    // 计算订单金额的辅助方法
    private Integer calculateAmount(ShoppingCartEntity cartItem) {
        // 验证modelID和computeID的互斥性
        if ((cartItem.getModelID() == null && cartItem.getComputeID() == null) ||
                (cartItem.getModelID() != null && cartItem.getComputeID() != null)) {
            throw new BusinessException("购物车项中modelID和computeID必须且只能存在一个");
        }

        // 根据模型计算金额
        if (cartItem.getModelID() != null) {
            ModelEntity model = modelService.getById(cartItem.getModelID());
            if (model == null) {
                throw new BusinessException("指定的模型不存在");
            }
            return calculateModelAmount(model, cartItem.getType(), cartItem.getQuantity());
        }
        // 根据计算资源计算金额
        else {
            ComputeEntity compute = computeService.getById(cartItem.getComputeID());
            if (compute == null) {
                throw new BusinessException("指定的计算资源不存在");
            }
            return calculateComputeAmount(compute, cartItem.getType(), cartItem.getQuantity());
        }
    }

    private Integer calculateModelAmount(ModelEntity model, ChargeTypeEnum type, Integer quantity) {
        switch (type) {
            case BY_TIMES:
                if (model.getPriceByTimes() == null) {
                    throw new BusinessException("该模型未设置按次计费价格");
                }
                return model.getPriceByTimes() * quantity;
            case BY_DAY:
                if (model.getPriceByDay() == null) {
                    throw new BusinessException("该模型未设置按天计费价格");
                }
                return model.getPriceByDay() * quantity;
            case BY_WEEK:
                if (model.getPriceByWeek() == null) {
                    throw new BusinessException("该模型未设置按周计费价格");
                }
                return model.getPriceByWeek() * quantity;
            case BY_MONTH:
                if (model.getPriceByMonth() == null) {
                    throw new BusinessException("该模型未设置按月计费价格");
                }
                return model.getPriceByMonth() * quantity;
            default:
                throw new BusinessException("不支持的收费类型");
        }
    }

    private Integer calculateComputeAmount(ComputeEntity compute, ChargeTypeEnum type, Integer quantity) {
        switch (type) {
            case BY_HOUR:
                if (compute.getPriceByHour() == null) {
                    throw new BusinessException("该计算资源未设置按小时计费价格");
                }
                return compute.getPriceByHour() * quantity;
            case BY_DAY:
                if (compute.getPriceByDay() == null) {
                    throw new BusinessException("该计算资源未设置按天计费价格");
                }
                return compute.getPriceByDay() * quantity;
            case BY_WEEK:
                if (compute.getPriceByWeek() == null) {
                    throw new BusinessException("该计算资源未设置按周计费价格");
                }
                return compute.getPriceByWeek() * quantity;
            case BY_MONTH:
                if (compute.getPriceByMonth() == null) {
                    throw new BusinessException("该计算资源未设置按月计费价格");
                }
                return compute.getPriceByMonth() * quantity;
            default:
                throw new BusinessException("不支持的收费类型");
        }
    }

    @Override
    public Integer calculateCartItemsAmount(List<String> cartItemIds, String modelCouponId, String computeCouponId) {
        if (cartItemIds == null || cartItemIds.isEmpty()) {
            throw new BusinessException("购物车商品ID列表不能为空");
        }

        // 获取当前用户
        UserEntity currentUser = userService.getCurrentUser();

        // 获取并验证购物车项
        int modelTotalAmount = 0;
        int computeTotalAmount = 0;
        for (String id : cartItemIds) {
            ShoppingCartEntity cartItem = shoppingCartService.getById(id);
            if (cartItem == null) {
                throw new BusinessException("购物车商品不存在：" + id);
            }

            // 验证购物车项是否属于当前用户
            if (!cartItem.getCreator().equals(currentUser.getId())) {
                throw new BusinessException("无权操作他人的购物车商品");
            }

            if (cartItem.getModelID() != null) {
                modelTotalAmount += calculateAmount(cartItem);
            } else {
                computeTotalAmount += calculateAmount(cartItem);
            }
        }
        return calculateDiscountedAmount(modelTotalAmount, computeTotalAmount, modelCouponId, computeCouponId);
    }

    @Override
    public Integer calculateOrdersAmount(List<CreateOrderDTO> createOrderDTOs, String modelCouponId, String computeCouponId) {
        if (createOrderDTOs == null || createOrderDTOs.isEmpty()) {
            throw new BusinessException("订单列表不能为空");
        }

        int modelTotalAmount = 0;
        int computeTotalAmount = 0;

        for (CreateOrderDTO orderDTO : createOrderDTOs) {
            // 验证modelID和computeID的互斥性
            if ((orderDTO.getModelID() == null && orderDTO.getComputeID() == null) ||
                    (orderDTO.getModelID() != null && orderDTO.getComputeID() != null)) {
                throw new BusinessException("modelID和computeID必须且只能存在一个");
            }

            // 根据模型计算金额
            if (orderDTO.getModelID() != null) {
                ModelEntity model = modelService.getById(orderDTO.getModelID());
                if (model == null) {
                    throw new BusinessException("指定的模型不存在");
                }
                modelTotalAmount += calculateModelAmount(model, orderDTO.getType(), orderDTO.getQuantity());
            }
            // 根据计算资源计算金额
            else {
                ComputeEntity compute = computeService.getById(orderDTO.getComputeID());
                if (compute == null) {
                    throw new BusinessException("指定的计算资源不存在");
                }
                computeTotalAmount += calculateComputeAmount(compute, orderDTO.getType(), orderDTO.getQuantity());
            }
        }
        return calculateDiscountedAmount(modelTotalAmount, computeTotalAmount, modelCouponId, computeCouponId);
    }

    private void addSortConditions(MPJLambdaWrapper<GoodsOrderEntity> queryWrapper, String sortType) {
        GoodsOrderSortTypeEnum.fromCode(sortType)
                .getSortFunction()
                .accept(queryWrapper);
    }

    private LocalDateTime calEndTime(GoodsOrderEntity goodsOrderEntity) {
        LocalDateTime endTime = LocalDateTime.now();
        if (goodsOrderEntity.getType() == ChargeTypeEnum.BY_HOUR) {
            endTime = endTime.plusHours(goodsOrderEntity.getQuantity());
        } else if (goodsOrderEntity.getType() == ChargeTypeEnum.BY_DAY) {
            endTime = endTime.plusDays(goodsOrderEntity.getQuantity());
        } else if (goodsOrderEntity.getType() == ChargeTypeEnum.BY_WEEK) {
            endTime = endTime.plusWeeks(goodsOrderEntity.getQuantity());
        } else if (goodsOrderEntity.getType() == ChargeTypeEnum.BY_MONTH) {
            endTime = endTime.plusMonths(goodsOrderEntity.getQuantity());
        }
        return endTime;
    }

    private void createComputeResource(GoodsOrderEntity goodsOrderEntity, ComputeEntity compute) {
        var endTime = calEndTime(goodsOrderEntity);
        String endTimeStr = endTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

//        var response = buaaComputeClient.resourceDeployment(compute.getGpuNumber(), compute.getCpuNumber(), compute.getMemorySize(), endTimeStr);
//
//        JSONObject data = JSONObject.parseObject(response.getBody()).getJSONObject("data");
//        JSONObject datainfo = data.getJSONObject("info");
//        computeResourceService.save(ComputeResourceEntity.builder()
//                .resourceId(data.getString("resourceId"))
//                .jupyterUrl(datainfo.getString("jupyterAddress"))
//                .sshCommand(datainfo.getString("sshCommand"))
//                .sshPassword(datainfo.getString("sshPassword"))
//                .owner(goodsOrderEntity.getBuyerID())
//                .compute(compute.getId())
//                .endTime(endTime)
//                .build());
        computeResourceService.save(ComputeResourceEntity.builder()
                .jupyterUrl("10.70.251.43:8888/lab")
                .sshCommand("ssh -p 22 buaa@10.70.251.43")
                .sshPassword("T0wjb02q")
                .owner(goodsOrderEntity.getBuyerID())
                .compute(compute.getId())
                .endTime(endTime)
                .build());
    }

    private void createModelResource(GoodsOrderEntity goodsOrderEntity, ModelEntity model) {
        var endTime = calEndTime(goodsOrderEntity);
        var modelAPIEntity = modelAPIService.getById(model.getFkModelApi());

        // 在API网关中为该次购买创建一个新的API转发地址
        String path;
        try {
            var response = kongAPIGatewayClient.createRoutesForService(modelAPIEntity.getKongServiceName());
            if (response.getStatusCode() != HttpStatus.CREATED) {
                throw new BusinessException(response.toString());
            }
            path = JSONObject.parseObject(response.getBody()).getJSONArray("paths").get(0).toString();
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }

        var modelResourceEntity = ModelResourceEntity.builder()
                .fkOwner(goodsOrderEntity.getBuyerID())
                .fkModel(goodsOrderEntity.getModelID())
                .chargeType(goodsOrderEntity.getType())
                .url(UriComponentsBuilder.fromHttpUrl(kongAPIGatewayConfig.getRequestBaseUrl())
                        .path(path)
                        .toUriString())
                .build();
        if (goodsOrderEntity.getType() == ChargeTypeEnum.BY_TIMES) {
            modelResourceEntity.setUsageTimes(goodsOrderEntity.getQuantity());
        } else {
            modelResourceEntity.setUsageTimes(-1);
            modelResourceEntity.setEndTime(endTime);
        }
        modelResourceService.save(modelResourceEntity);
    }

}
